#include <sys/types.h>          
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include "log.hpp"

const int backlog = 10;
const uint16_t DefalutPort = 8080;

class Sock
{
public:

    Sock()
    :_sockfd(0)
    {

    }

    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd < 0)
        {
            log(Fatal, "socket fail, errno is %d, error message is: %s", errno, strerror(errno));
            exit(-1);
        }
        log(Debug, "Socket Debuging...");
    }

    void Bind(uint16_t port = DefalutPort)
    {
        sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        int res = bind(_sockfd, (sockaddr*)(&local), sizeof(local));

        if(res < 0)
        {
            log(Fatal, "bind fail, errno is %d, error message is: %s", errno, strerror(errno));
            exit(-1);
        }
        log(Debug, "Bind Debuging...");
    }

    void Listen()
    {
       if(listen(_sockfd, backlog) < 0)
       {
            log(Fatal, "listen fail, errno is %d, error message is: %s", errno, strerror(errno));
            exit(-1);        
       }
       log(Debug, "Listen Debuging...");
    }

    //返回三部分信息：newfd，客户端ip，客户端port
    int Accpet(string* clientip, uint16_t* clientport)
    {
        sockaddr_in client;
        socklen_t len = sizeof(client);
        int newfd = accept(_sockfd, (sockaddr*)(&client), &len);
        if(newfd < 0)
        {
            log(Warning, "accept fail, errno is %d, error message is: %s", errno, strerror(errno)); 
        }

        if(clientip != nullptr && clientport != nullptr)
        {
            *clientip = inet_ntoa(client.sin_addr);
            *clientport = client.sin_port;            
        }
        return newfd;
    }

    void Connect(string& clientip, uint16_t clientport)
    {
        sockaddr_in server;
        
        server.sin_family = AF_INET;
        server.sin_port = htons(clientport);
        inet_aton(clientip.c_str(),&server.sin_addr);   //先设置服务器才知道连接的是哪个服务器！

        socklen_t len = sizeof(server);
        int res = connect(_sockfd,(sockaddr*)(&server), len);
        if(res < 0)
        {
            log(Warning, "connect fail, errno is %d, error message is: %s", errno, strerror(errno)); 
        }
    }

    void Close()
    {
        close(_sockfd);
    }

    int GetFd(){return _sockfd;}
    
private:
    int _sockfd;
};